import config from './WebIMConfig'
import { isBrowser } from '@/utils/util'
import Emoji from '@/static/IM/js/emoji.js'

// const noticeId = store.getters.noticeID
// console.log(noticeId)
// import emedia from 'easemob-emedia'// 单人音视频sdk
// import webrtc from 'easemob-webrtc'// 多人音视频sdk

var websdk = ''
// 播放语音铃声
// function playBell(type) {
//   var audio = document.createElement('audio')
//   audio.controls = true
//   audio.src = '//static.rongcat.com/audio/' + type + '.mp3'
//   audio.play()
// }
async function webIM() {
  try {
    if (isBrowser()) {
      // 初始化IM SDK
      await import(/* webpackChunkName: "MyFile" */'easemob-websdk').then(res => {
        websdk = res.default
      })
      var WebIM = {}
      WebIM = window.WebIM = websdk
      WebIM.config = config
      WebIM.Emoji = Emoji
      WebIM.conn = new WebIM.connection({
        appKey: WebIM.config.appkey,
        isHttpDNS: WebIM.config.isHttpDNS,
        isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
        https: WebIM.config.https,
        url: WebIM.config.xmppURL,
        apiUrl: WebIM.config.apiURL,
        isAutoLogin: true,
        heartBeatWait: WebIM.config.heartBeatWait,
        autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
        autoReconnectInterval: WebIM.config.autoReconnectInterval,
        isStropheLog: WebIM.config.isStropheLog,
        delivery: WebIM.config.delivery
      })
      if (!WebIM.conn.apiUrl) {
        WebIM.conn.apiUrl = WebIM.config.apiURL
      }

      // window.$nuxt.$store.dispatch('userInfo')

      WebIM.conn.listen({
        onOpened: function(message) { // 连接成功回调
          setTimeout(() => {
            console.log('客服已上线')
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '客服已上线', type: 'success' })
          }, 2000)
        },
        onClosed: function(message) {
          setTimeout(() => {
            window.$nuxt.$store.dispatch('userInfo')
          }, 2000)
        }, // 连接关闭回调
        onOnline: function() {
          console.log('onLine')// 本机网络连接成功
        },
        onOffline: function() {
          // console.log('offline')// 本机网络掉线
          window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '网络已断开，请检查网络', type: 'error' })
        },
        onTextMessage: function(message) {
          console.log('onTextMessage', message)
          message.message_type = 'txt'
          window.$nuxt.$store.dispatch('IM/receiveMessage', message)
          // if (parseInt(message.from) === parseInt(noticeId)) {
          //   playBell('kehu')
          //   store.dispatch('IM/receiveNotification', message)
          // } else {
          //   playBell('zixun')
          //   store.dispatch('IM/receiveMessage', message)
          // }
        }, // 收到文本消息
        onEmojiMessage: function(message) {
          // console.log('IM文本消息', message)
          var message_str = ''
          var data = message.data
          for (var i = 0, l = data.length; i < l; i++) {
            // console.log(data[i])
            switch (data[i].type) {
              case 'emoji':
                message_str += '<img class="emoji" src="' + data[i].data + '" />'
                break
              case 'txt':
                message_str += data[i].data
                break
              default:
                message_str += data[i].data
            }
          }
          message.data = message_str
          message.message_type = 'txt'
          // console.log(message)
          // playBell('zixun')
          window.$nuxt.$store.dispatch('IM/receiveMessage', message)
        }, // 收到表情消息
        onPictureMessage: function(message) {
          message.data = '<img class="message-img" src="' + message.url + '" />'
          message.message_type = 'img'
          // playBell('zixun')
          window.$nuxt.$store.dispatch('IM/receiveMessage', message)
        }, // 收到图片消息
        onCmdMessage: function(message) {
          // console.log('onCmdMessage', message)
        }, // 收到命令消息
        onAudioMessage: function(message) {
          console.log('IM语音消息', message)
          const options = {
            url: message.url,
            headers: { Accept: 'audio/mp3' },
            onFileDownloadComplete: function(response) {
              // console.log(response)
              var objectURL = WebIM.utils.parseDownloadResponse.call(WebIM.conn, response)
              var message_str = '<audio id="' + message.id + '" preload="auto">' +
             '<source src="' + objectURL + '" type="audio/mpeg">' +
             '</audio>'
              var message_ext = '<div class="audio-box">' +
             '<div class="audio-symbol">' +
             '<div class="first"/>' +
             '<div class="second"/>' +
             '<div class="third"/>' +
             '</div>' +
             '</div>'
              message.data = message_str
              message.message_type = 'audio'
              message.message_ext = message_ext
              // playBell('zixun')
              window.$nuxt.$store.dispatch('IM/receiveMessage', message)
            },
            onFileDownloadError: function() {
              // console.log('音频下载失败')
            }
          }
          WebIM.utils.download.call(WebIM.conn, options)
        },
        onError: function(message) {
          if (message.type === 16) {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '客服已断开，正在重新连接……', type: 'error' })
          } else if (message.type === 28) {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '客服未登录，刷新页面或请重新登陆系统', type: 'error' })
          } else if (message.type === 504) {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '消息撤回失败', type: 'error' })
          } else if (message.type === 206) {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '账号重复登录,请检查是否有其他人或者您浏览器的其他窗口打开容猫通', type: 'error' })
          } else if (message && message.data && message.data.data && message.data.data.error_description === 'user not found') {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '用户名不存在', type: 'error' })
          } else if (message && message.data && message.data.data && message.data.data.error_description === 'invalid password') {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '密码无效', type: 'error' })
          } else if (message && message.data && message.data.data && message.data.data.error_description === 'user not activated') {
            window.$nuxt.$store.dispatch('IM/onMsgAlert', { show: true, title: '用户已被封禁', type: 'error' })
          }
        }, // 失败回调
        onRecallMessage: message => {
          // console.log('onRecallMessage', message)
          message.status = 'recall'
          message.msg = '对方撤回了一条消息'
          window.$nuxt.$store.commit('IM/updateMessageStatus', message)
        },
        onReceivedMessage: function(message) {
          // console.log('onReceivedMessage', message)
          window.$nuxt.$store.dispatch('IM/updateMessageMid', message)
          message.status = 'sent'
          window.$nuxt.$store.dispatch('IM/updateMessageStatus', message)
        }, // 收到消息送达服务器回执
        onDeliveredMessage: function(message) {
          // console.log('onDeliveredMessage', message)
        }, // 收到消息送达客户端回执

        onReadMessage: function(message) {
          // console.log('onReadMessage', message)
          message.status = 'read'
          window.$nuxt.$store.dispatch('IM/updateMessageStatus', message)
        } // 收到消息已读回执
      })
      // 注册监听回调

      // 音视频
      // WebIM.WebRTC = webrtc
      // WebIM.EMedia = emedia
      return WebIM
    }
  } catch (e) {
    console.log('WebIM:::::::', e)
  }
}

export default webIM()
